import { getById, saveDict } from '@/api/sys/dictChildren'
import useForm from '@/hooks/useForm'
import { computed, defineComponent, PropType, watch } from 'vue'
import { IDictChildrenType } from '.'

export default defineComponent({
  name: 'DictTypeForm',
  props: {
    visible: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    formId: {
      type: String as PropType<string>,
      default: ''
    },
    dictType: {
      type: String as PropType<string>,
      default: ''
    }
  },
  setup(props, { emit }) {
    const { closeDialog, state, formRef } = useForm<IDictChildrenType>(emit, props.formId)
    const formRules = {
      dictValue: [
        { required: true, message: 'required', trigger: 'blur' }
      ],
      code: [
        { required: true, message: 'required', trigger: 'blur' }
      ]
    }

    const handleOk = () => {
      formRef.value.validate().then(() => {
        saveDict({ ...state.form, bookType: props.dictType }).then((res) => {
          if (res.state) {
            closeDialog()
          }
        })
      })
    }

    watch(computed(() => props.formId), (formId) => {
      if (formId) {
        getById(formId).then((res) => {
          state.form = res.result.form
        })
      } else {
        state.form = {}
      }
    }, { immediate: true })

    return () => {
      return (
        <a-modal
          visible={props.visible}
          title="Modal"
          ok-text="确认"
          cancel-text="取消"
          onCancel={closeDialog}
          onOk={handleOk}
        >
          <a-form
            rules={formRules}
            ref={formRef}
            model={state.form}
          >
            <a-form-item has-feedback label="标志" name="dictValue">
              <a-input v-model={[state.form.dictValue, 'value']} autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="key值" name="code">
              <a-input v-model={[state.form.code, 'value']} autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="排序" name="dictOrder">
              <a-input-number v-model={[state.form.dictOrder, 'value']} />
            </a-form-item>
          </a-form>
        </a-modal>
      )
    }
  }
})
